<?php
/**
 * @author wesley
 * @version v1.0
 * @time 2021/6/30 11:10
 * @desc
 */

namespace app\lib\exception;

use think\Exception;
use think\exception\Handle;
use think\facade\Log;
use think\Response;
use Throwable;

class ExceptionHandler extends Handle
{
    public function render($request, Throwable $e): Response
    {
        if ($e instanceof BaseException) {
//            自定义异常
            $code = $e->code;
            $msg = $e->msg;
            $errorCode = $e->errorCode;
        } else {
            if(env('APP_DEBUG','0')){
                return parent::render($request,$e);
            }else {
                $code = 500;
                $msg = '服务器内部错误';
                $errorCode = 999;
                $this->recordErrorLog($e);
            }

        }
        $result = [
            'msg' => $msg,
            'error_code' => $errorCode,
            'request_url' => $request->url()
        ];
        return json($result, $code);
    }
    private function recordErrorLog(Throwable $e): void
    {
        Log::record($e->getMessage(),'warning');
    }
}